const formatTime = date => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();

    return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second]
        .map(formatNumber)
        .join(':')}`;
};

const formatNumber = n => {
    n = n.toString();
    return n[1] ? n : `0${n}`;
};

// 网络请求API地址
const baseURL = 'http://www.geonoon.com/data/indoorPositioning/wechat_map_data/';
/**
 * @function 封装网络请求
 * @param {*} requestData
 * @param  {...any} other
 */
const wxRequest = (requestData, ...other) => {
    console.log(requestData);
    return new Promise((resolve, reject) => {
        wx.request({
            url: baseURL + requestData.url,
            data: requestData.data,
            method: requestData.method || 'GET',
            ...other,
            success(res) {
                console.log('resolve');
                console.log(res);
                resolve(res);
            },
            fail(res) {
                console.log(res.statusCode);
                reject();
            },
        });
    });
};
/**
 * @function 拼接requestData
 * @param {string} url
 * @param  {...any} rest
 * @returns
 */
const joinUrl = (url, ...rest) => {
    return {
        url: url,
        data: '',
        method: '',
    };
};
/**
 * @function isComplexDataType 判读入参是否为对象
 * @param {*} obj
 */
const isComplexDataType = obj =>
    (typeof obj === 'object' || typeof obj === 'function') && obj !== null;

/**
 * @function deepClone 深拷贝
 * @param {*} obj
 * @param {*} hash
 */
const deepClone = function (obj, hash = new WeakMap()) {
    if (obj.constructor === Date) return new Date(obj); // 日期对象直接返回一个新的日期对象
    if (obj.constructor === RegExp) return new RegExp(obj); //正则对象直接返回一个新的正则对象
    //如果循环引用了就用 weakMap 来解决
    if (hash.has(obj)) return hash.get(obj);
    let allDesc = Object.getOwnPropertyDescriptors(obj);
    //遍历传入参数所有键的特性
    let cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc);
    //继承原型链
    hash.set(obj, cloneObj);
    for (let key of Reflect.ownKeys(obj)) {
        cloneObj[key] =
            isComplexDataType(obj[key]) && typeof obj[key] !== 'function'
                ? deepClone(obj[key], hash)
                : obj[key];
    }
    return cloneObj;
};

module.exports = {
    formatTime,
    isComplexDataType,
    deepClone,
    wxRequest,
    joinUrl,
};
